const express = require("express");
const router = express.Router();
const path = require("path");

const baseConfig = require("./router/baseConfig")
router.use(baseConfig)

const mysql = require("mysql");
const pool = mysql.createPool(config.dbPool);

router.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/generate/index.html"));
});
router.get("/1", (req, res) => {
  res.sendFile(path.join(__dirname + "/test.html"));
});

router.post("/create", (req, res) => {
  const { tableName, fields } = req.body;

  // 创建 SQL 语句
  let sql = `CREATE TABLE ${tableName} (`;

  fields.forEach((field, index) => {
    sql += `${field.name} ${field.type}`;

    if (field.length) {
      sql += `(${field.length})`;
    }

    if (field.decimals) {
      sql += `(${field.length},${field.decimals})`;
    }

    if (field.unsigned) {
      sql += " UNSIGNED";
    }

    if (field.notNull) {
      sql += " NOT NULL";
    }

    if (field.primaryKey) {
      sql += " PRIMARY KEY";
    }

    if (field.defaultValue) {
      sql += ` DEFAULT '${field.defaultValue}'`;
    }

    if (field.comment) {
      sql += ` COMMENT '${field.comment}'`;
    }

    if (field.charset) {
      sql += ` CHARACTER SET ${field.charset}`;
    }

    if (field.collate) {
      sql += ` COLLATE ${field.collate}`;
    }

    if (index !== fields.length - 1) {
      sql += ", ";
    }
  });

  sql += ")";
  console.log(sql);

  // 执行 SQL 语句
  pool.query(sql, (err, result) => {
    if (err) {
      console.log(err);
      res.status(500).send("Error creating table");
      return;
    }
    res.send("Table created successfully");
  });
});

module.exports = router;
